package com.oto.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;


import org.springframework.stereotype.Service;

import com.oto.Constants;
import com.oto.model.PackDO;

/**
 * @author xueqiang.mi
 * @since 2010-11-27
 */
@Service
public class PackService extends BaseService {

	public void add(PackDO p) {
		Date now = new Date();
		p.setCrtDate(now);
		p.setModDate(now);

		save(p);
	}

	public void createDefaultPackForUSer(String owner) {
		createPackForUser(Constants.DEFAULT_PACK_NAME, owner);
	}

	public void createPackForUser(String name, String owner) {
		PackDO p = new PackDO();
		p.setName(name);
		p.setOwner(owner);

		add(p);
	}

	public void del(Long id) {
		delete(PackDO.class, id);
	}

	public PackDO get(Long id) {
		return get(PackDO.class, id);
	}

	public PackDO getDefaultPack(String owner) {
		return getPack(Constants.DEFAULT_PACK_NAME, owner);
	}

	@SuppressWarnings("unchecked")
	public PackDO getPack(String name, String owner) {
		PersistenceManager pm = PMF.get();
		Query query = pm.newQuery(PackDO.class);
		query.setFilter("name == '" + name + "' && owner == '" + owner + "'");
		Collection<PackDO> c = (Collection<PackDO>) query.execute();
		if (c != null && c.size() == 1) {
			return (PackDO) c.toArray()[0];
		}
		return null;
	}

	public List<PackDO> list() {
		return list(PackDO.class);
	}

	@SuppressWarnings("unchecked")
	public List<PackDO> getByUser(String userName) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(PackDO.class);
			query.setFilter("owner == :owner");
			query.setOrdering("rating desc");
			Collection<PackDO> c = pm.detachCopyAll((Collection<PackDO>) query.execute(userName));
			return new ArrayList<PackDO>(c);
		} finally {
			pm.close();
		}
	}
}
